package cn.hicard.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class IOHelper {
	
	/**
	 * 将指定输入流写到指定输出流
	 * @param input
	 * @param output
	 * @throws IOException
	 */
	public static void writeTo(InputStream input, OutputStream output) throws IOException{
		byte[] buff = new byte[1024];
		int len = 0;
		while((len = input.read(buff))>=0){
			output.write(buff, 0, len);
		}
		output.flush();
		output.close();
		input.close();
		
	}
	
	/**
	 * 将指定数据流写到指定路径的文件（会覆盖已存在的文件）
	 * @param input
	 * @param filepath
	 * @throws IOException
	 */
	public static void writeTo(InputStream input, String filepath) throws IOException{
		IOHelper.writeTo(input, new File(filepath));
	}
	
	/**
	 * 将指定数据流写到指定的文件（会覆盖已存在的文件）
	 * @param input
	 * @param file
	 * @throws IOException
	 */
	public static void writeTo(InputStream input, File file) throws IOException{
		FileOutputStream fos = new FileOutputStream(file);
		IOHelper.writeTo(input, fos);
	}
	
	/**
	 * 读取输入流所有数据作为指定字符集编码的字符串输出
	 * @param input
	 * @param charset
	 * @return
	 * @throws IOException
	 */
	public static String read(InputStream input, String charset) throws IOException{
		BufferedReader reader = new BufferedReader(new InputStreamReader(input, charset));
		StringBuilder sb = new StringBuilder();
		String line = null;
		while((line = reader.readLine()) != null){
			sb.append(line);			
		}
		input.close();
		return sb.toString();
	}

}
